// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {

  const tempResult = await cloud.database().collection("signUp").where({
    gameId: event.gameId,
    state: "成功"
  }).orderBy('city', 'desc').orderBy('school', 'desc').get({
    success: res => {
      console.log("获取通过报名数据成功", res)
    },
    fail: res => {
      console.log("获取通过报名数据成功", res)
    }
  })
  // console.log(tempResult)

  // 更新考号
  for (let i = 0; i < tempResult.data.length; ++i) {
    let tempNumber = i + 1
    let tempString = tempNumber.toString()
    while (tempString.length < 4) {
      tempString = "0" + tempString
    }
    console.log(tempString)
    tempResult.data[i].contestant_id = "GD-" + tempString
    console.log(tempResult.data[i].contestant_id)
  }

  
  
  for (let i = 0; i < tempResult.data.length; ++i) {
    cloud.database().collection("signUp").where({
      gameId: event.gameId,
      "user._id": tempResult.data[i].userId
    }).update({
      data: {
        contestant_id: tempResult.data[i].contestant_id
      },
      success: res => {
        console.log("获取更新考号成功", res)    
      },
      fail: res => {
        console.log("获取更新考号失败", res)
      }
    })
  }
}